<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '个人资料',
  },
}
</route>

<template>
  <view class="container">
    <wd-cell title="头像" vertical>
      <view class="avatar-row">
        <wd-upload
          :action="uploadAction"
          accept="image"
          :limit="1"
          :show-file-list="false"
          :preview-image="false"
          :deletable="false"
          @success="onUploadSuccess"
        >
          <image v-if="avatarUrl" :src="avatarUrl" class="avatar" mode="aspectFill" />
          <wd-button v-else size="small" type="primary">更换头像</wd-button>
        </wd-upload>
      </view>
    </wd-cell>

    <wd-cell title="昵称" vertical>
      <wd-input v-model="nickName" placeholder="请输入昵称" />
    </wd-cell>

    <view class="actions">
      <wd-button type="primary" block @click="onSave">保存</wd-button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { httpGet, httpPost } from '@/utils/http'
import { getEnvBaseUploadUrl } from '@/utils'
import type { UploadFile } from 'wot-design-uni/components/wd-upload/types'

const defaultAvatar = '/static/images/kefu.png'
const nickName = ref('')
const avatarUrl = ref('')

const getUserInfo = async () => {
  const info: any = await httpGet('/api/app/user/info/person')
  nickName.value = info?.nickName || ''
  avatarUrl.value = info?.avatarUrl || ''
}

getUserInfo()

const uploadAction = getEnvBaseUploadUrl()

function onUploadSuccess(res: any) {
  if (res?.file?.response) {
    try {
      const parsed = JSON.parse(res.file.response)
      avatarUrl.value = parsed?.data || ''
    } catch {
      avatarUrl.value = String(res.file.response)
    }
  }
}

async function onSave() {
  await httpPost('/api/app/user/info/updatePerson', {
    nickName: nickName.value,
    avatarUrl: avatarUrl.value,
  })
  uni.showToast({ title: '保存成功' })
}
</script>

<style lang="scss" scoped>
.container {
  padding: 24rpx;
}
.avatar-row {
  display: flex;
  align-items: center;
  gap: 20rpx;
}
.avatar-row :deep(.wd-upload) {
  width: auto;
}
.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background: #f5f5f5;
}
.actions {
  margin-top: 40rpx;
}
</style>
